package com.chenfeng.blog.controller;

import com.chenfeng.blog.domian.User;
import com.chenfeng.blog.responsitory.UserRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebParam;

/**
 * Created by wrcsh on 2018/8/2.
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserRespository userRespository;

    /**
     * 查询所有用户
     * @param model
     * @return
     */
    @GetMapping
    public ModelAndView list(Model model){
        model.addAttribute("userList", userRespository.getListUser());
        model.addAttribute("title","用户管理");
        return  new ModelAndView("users/list", "userModel", model);
    }

    /**
     * 根据ID查询用户
     * @param id
     * @param model
     * @return
     */
    @GetMapping("{id}")
    public ModelAndView view(@PathVariable("id") Long id, Model model){
        User user = userRespository.getUserById(id);
        model.addAttribute("user", user);
        model.addAttribute("title", "查看用户");
        return  new ModelAndView("users/list", "userModel", model);
    }

    /**
     * 创建
     * @param model
     * @return
     */
    @GetMapping("/form")
    public ModelAndView createForm(Model model){
        model.addAttribute("user", new User());
        model.addAttribute("title", "创建用户");
        return  new ModelAndView("users/form", "userModel", model);
    }

    /**
     * 保存或修改用户
     * @param user
     * @return
     */
    @PostMapping
    public ModelAndView saveOrUpade(User user){
        userRespository.saveOrupdateUser(user);

        return  new ModelAndView("redirect:/users");
    }

    @GetMapping("delete/{id}")
    public ModelAndView delete(@PathVariable("id") Long id, Model model){
        userRespository.deleteUser(id);
        return  new ModelAndView("redirect:/users");
    }
}
